/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert.support;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;

import com.tengtong.duang.commons.convert.ConditionalConverter;
import com.tengtong.duang.commons.convert.ConversionService;
import com.tengtong.duang.commons.convert.ConvertiblePair;
import com.tengtong.duang.commons.utils.ReflectUtils;

/**
 * Collection 转  Array
 *
 * @author jai
 * @since: v1.0
 */
public class CollectionToArrayConverter implements ConditionalConverter{

	private final ConversionService helperConverter;
	
	public CollectionToArrayConverter(ConversionService helperConverter){
		this.helperConverter = helperConverter;
	}
	
	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#convert(java.lang.Object, java.lang.Class)
	 */
	@Override
	public Object convert(Object source, Class targetType) {
		if (source == null) {
			return null;
		}
		Collection<?> sourceCollection = (Collection<?>) source;
		Object array = Array.newInstance(targetType.getComponentType(), sourceCollection.size());
		int i = 0;
		for (Object sourceElement : sourceCollection) {
			Object targetElement = this.helperConverter.convert(sourceElement, targetType.getComponentType());
			Array.set(array, i++, targetElement);
		}
		return array;
	}

	/* (non-Javadoc)
	 * @see com.tengtong.duang.commons.convert.ConditionalConverter#matches(java.lang.Class, java.lang.Class)
	 */
	@Override
	public boolean matches(Class<?> sourceType, Class<?> targetType) {
		return ReflectUtils.isInheritance(sourceType, Collection.class) && targetType.isArray();
	}
}
